package com.xyhuo.leetcode.december;

/**
 * 最长公共前缀
 * https://leetcode.cn/problems/longest-common-prefix/
 *
 * @time 2023/12/5
 */
public class LongestCommonPrefix {

//    public static void main(String[] args) {
//        LongestCommonPrefix lc = new LongestCommonPrefix();
//        String[] strs = {""};
//        String s = lc.longestCommonPrefix(strs);
//        System.out.println(s);
//    }

    public String longestCommonPrefix(String[] strs) {
        int index = 0;
        int length = strs.length;
        char[][] chars = new char[length][];
        for (int i = 0; i < length; i++) {
            chars[i] = strs[i].toCharArray();
        }
        while (true) {
            boolean pre = true;
            if (index >= chars[0].length) {
                pre = false;
            } else {
                char tmp = chars[0][index];
                for (int i = 1; i < length; i++) {
                    if (index >= chars[i].length) {
                        pre = false;
                        break;
                    }
                    if (chars[i][index] != tmp) {
                        pre = false;
                        break;
                    }
                }
            }
            if (!pre) {
                break;
            }
            index++;
        }
        if (index == 0) {
            return "";
        }
        return strs[0].substring(0, index);
    }
}
